<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    function urlToBase64(url) {
        return new Promise((res, rej) => {
          const img = new Image();
          img.onload = function () {
            const canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight;
            // 将图片插入画布并开始绘制
            canvas.getContext('2d').drawImage(img, 0, 0);
            const result = canvas.toDataURL('image/png');
            resolve(result);
          }
          // 会存在跨域问题,https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
          img.setAttribute('crossOrigin', 'anonymous');
          img.src = url;
          img.onerror = () => rej('image stream error');
        });
      }

      console.log(urlToBase64('/Users/zhangzhijin/Desktop/picture/weixin.png'));
  </script>
</body>
</html>